/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.helpdesk.controllers.util;

import java.lang.reflect.Field;
import java.util.Comparator;
import org.primefaces.model.SortOrder;

/**
 *
 * @author JK
 */
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
public class LazySorter<T> implements Comparator<T> {

    private String sortField;
    private SortOrder sortOrder;

    public LazySorter(String sortField, SortOrder sortOrder) {
        this.sortField = sortField;
        this.sortOrder = sortOrder;
    }

    @Override
    public int compare(T o, T o1) {
        try {
            Field field1 = o.getClass().getDeclaredField(this.sortField);
            Field field2 = o1.getClass().getDeclaredField(this.sortField);
            if (field1 != null && field2 != null) {
                field1.setAccessible(true);
                field2.setAccessible(true);
                Object value1 = field1.get(o);
                Object value2 = field2.get(o1);

                int value = ((Comparable) value1).compareTo(value2);

                return SortOrder.ASCENDING.equals(sortOrder) ? value : -1 * value;
            } else {
                throw new RuntimeException("field not valid");
            }

        } catch (Exception e) {
            throw new RuntimeException();
        }
    }
}
